package com.java214.elec.dao.impl;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.java214.elec.dao.ICommonDao;
import com.java214.elec.utils.GenericTypeUtils;

/**   
*    
* 项目名称：MyEleManagerSys   
* 类名称：公用CommonDaoImpl实现类   HibernateDaoSupport模板类
* 类描述：   实现类
* 创建人：君无邪   
* 创建时间：2019年11月12日 上午2:09:40   
* 修改备注：  https://www.java214.com 
* @version    1.0
*    
*/ 
public class CommonDaoImpl<T> extends HibernateDaoSupport implements ICommonDao<T> {

	Class entityClass = GenericTypeUtils.getGenericSuperClass(this.getClass());
	
	/**
	 * spring容器中定义
	 * <bean id="commonDao" class="cn.itcast.elec.dao.impl.CommonDaoImpl">
		<property name="sessionFactory" ref="sessionFactory"></property>
	  * </bean>
	 */
	@Resource(name="sessionFactory")
	public final void setSessionFactoryDi(SessionFactory sessionFactory) {
		this.setSessionFactory(sessionFactory);
	}
	
	
	//保存
	@Override
	public Integer save(T entity) {
		// TODO Auto-generated method stub
		Integer n=0;
		try {
			this.getHibernateTemplate().save(entity);
			n=1;
			System.out.println(n+"保存成功");
		} catch (Exception e) {
			// TODO: handle exception
e.printStackTrace();
			n=0;
			System.out.println("保存出错"+n);
		}
	
		
		
		
		return n;
	}

	//更新
	@Override
	public Integer update(T entity) {
		Integer n=0;
		try {
			this.getHibernateTemplate().update(entity);
			n=1;
			System.out.println(n+"更新成功");
		} catch (Exception e) {
			// TODO: handle exception
e.printStackTrace();
			n=0;
			System.out.println("更新出错"+n);
		}
	
		
		
		
		return n;
	}


	//使用主键ID查询
	@Override
	public T findObjectById(Serializable id) {
		// TODO Auto-generated method stub
		//泛型转换
	Class bean=	GenericTypeUtils.getGenericSuperClass(this.getClass());

		return 		(T) this.getHibernateTemplate().get(bean, id);
	}


	//删除/批量删除
	@Override
	public Integer deleteBojectByIDs(Serializable... ids) {
		// TODO Auto-generated method stub
		Integer n=0;
		try {	
			if(ids!=null && ids.length>0){
			for (Serializable id : ids) {
				T bean = this.findObjectById(id);
				this.getHibernateTemplate().delete(bean);
				n=1;
			}
		}
			return n;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			System.out.println("删除/批量删除出错");
			n=0;
			return n;
		}
	
	
	}

	//集合删除
	@Override
	public Integer deleteObjectByCollection(List<T> list) {
		// TODO Auto-generated method stub
		Integer n=0;
		try {
			this.getHibernateTemplate().deleteAll(list);
			n=1;
			System.out.println("集合删除成功:"+n);
			return n;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			n=0;
			System.out.println("集合删除失败:"+n);
			return n;
		}


	}

	/**指定页面传递的查询条件，查询对应的结果集信息，返回List<ElecText>，不分页*/
	/**
	SELECT * FROM elec_text o WHERE 1=1      #Dao层
	AND o.textName LIKE '%张%'           #Service层
	AND o.textRemark LIKE '%张%'         #Service层
	ORDER BY o.textDate ASC,o.textRemark DESC  #Service层
 */
	@SuppressWarnings("unchecked")
	public List<T> findCollectionByConditionNoPage(String condition,
			final Object[] params, Map<String, String> orderby) {
		String hql = "select o from "+entityClass.getSimpleName()+" o where 1=1 ";
		//解析map集合，获取排序的语句
		String orderbyhql = this.orderby(orderby);
		final String finalHql = hql + condition + orderbyhql;
		//方式一
		//List<T> list = this.getHibernateTemplate().find(finalHql, params);
		//方式二，使用hibernate模板提供的回调函数，回调Session
		List<T> list = this.getHibernateTemplate().execute(new HibernateCallback() {

			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query = session.createQuery(finalHql);
				if(params!=null && params.length>0){
					for(int i=0;i<params.length;i++){
						query.setParameter(i, params[i]);
					}
				}
				return query.list();
			}
		});
		System.out.println(list+".......查询出来的数据 ");
		return list;
	}


//解析map集合，获取排序的语句，ORDER BY o.textDate ASC,o.textRemark DESC
	private String orderby(Map<String, String> orderby) {
		StringBuffer buffer = new StringBuffer("");
		if(orderby!=null && orderby.size()>0){
			buffer.append(" order by ");
			for(Map.Entry<String, String> map:orderby.entrySet()){
				buffer.append(map.getKey()+" "+map.getValue()+",");
			}
			//删除最后一个逗号
			buffer.deleteCharAt(buffer.length()-1);
		}
		return buffer.toString();
	}
	
	/**添加二级缓存，针对数据字典*/
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public List<T> findCollectionByConditionNoPageCache(String condition,
			final Object[] params, Map<String, String> orderby) {
		String hql = "select o from "+entityClass.getSimpleName()+" o where 1=1 ";
		//解析map集合，获取排序的语句
		String orderbyhql = this.orderby(orderby);
		final String finalHql = hql + condition + orderbyhql;
		//方式一
		//List<T> list = this.getHibernateTemplate().find(finalHql, params);
		//方式二，使用hibernate模板提供的回调函数，回调Session
		List<T> list = this.getHibernateTemplate().execute(new HibernateCallback() {

			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query = session.createQuery(finalHql);
				if(params!=null && params.length>0){
					for(int i=0;i<params.length;i++){
						query.setParameter(i, params[i]);
					}
				}
				query.setCacheable(true);
				return query.list();
			}
		});
		return list;
	}

	/**指定页面传递的查询条件，查询对应的结果集信息，返回List<ElecText>，分页*/
	/**
		SELECT * FROM elec_text o WHERE 1=1      #Dao层
		AND o.textName LIKE '%张%'           #Service层
		AND o.textRemark LIKE '%张%'         #Service层
		ORDER BY o.textDate ASC,o.textRemark DESC  #Service层
	 */
	/*@SuppressWarnings({ "unchecked", "rawtypes" })
	public List<T> findCollectionByConditionWithPage(String condition,
			final Object[] params, Map<String, String> orderby,final PageInfo pageInfo) {
		String hql = "select o from "+entityClass.getSimpleName()+" o where 1=1 ";
		//解析map集合，获取排序的语句
		String orderbyhql = this.orderby(orderby);
		final String finalHql = hql + condition + orderbyhql;
		List<T> list = this.getHibernateTemplate().execute(new HibernateCallback() {

			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query = session.createQuery(finalHql);
				if(params!=null && params.length>0){
					for(int i=0;i<params.length;i++){
						query.setParameter(i, params[i]);
					}
				}
				*//**2013-11-30 添加分页 begin*//*
				pageInfo.setTotalResult(query.list().size());//先获取检索数据的总记录数
				query.setFirstResult(pageInfo.getBeginResult());//当前页从第几条开始检索，0表示第1条记录（默认值）
				query.setMaxResults(pageInfo.getPageSize());//当前页最多显示多少条记录
				*//**2013-11-30 添加分页 end*//*
				return query.list();
			}
		});
		return list;
	}*/
	
	
	/**
	 * 按照投影条件查询对应的结果（一般用在动态导出excel）
	SELECT selectCondition FROM elec_text o WHERE 1=1      #Dao层
	AND o.textName LIKE '%张%'           #Service层
	AND o.textRemark LIKE '%张%'         #Service层
	ORDER BY o.textDate ASC,o.textRemark DESC  #Service层
 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public List findCollectionByConditionNoPageWithSelectCondition(String condition,
			final Object[] params, Map<String, String> orderby,String selectCondition) {
		String hql = "select "+selectCondition+" from "+entityClass.getSimpleName()+" o where 1=1 ";
		//解析map集合，获取排序的语句
		String orderbyhql = this.orderby(orderby);
		final String finalHql = hql + condition + orderbyhql;
		List<T> list = this.getHibernateTemplate().execute(new HibernateCallback() {
	
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query = session.createQuery(finalHql);
				if(params!=null && params.length>0){
					for(int i=0;i<params.length;i++){
						query.setParameter(i, params[i]);
					}
				}
				return query.list();
			}
		});
		return list;
	}
}
